package com.sunbeam.common.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import com.sunbeam.common.consts.EConstants;
import com.sunbeam.common.junit.accessories.StaffInfoEntity;

/**
 * Read Dom Utils
 * @ClassName: XmlCommonUtils
 * @Description: TODO
 * @author lyz lyzpoq_gmail_com
 * @date 2014/01/09 9:42:54
 */
public class XmlCommonUtils{

    public static void main (String argv []){
    readStaffInfos();

    }//end of main

    public static List<StaffInfoEntity> getStaffInfos(){
    	List<StaffInfoEntity> staffInfos=new ArrayList<StaffInfoEntity>();
    	StaffInfoEntity staffInfo=null;
		try {
			String ConfigFilePath = StringUtils.URLPathCombine(new String[] {XmlUtils.class.getClassLoader().getResource("").getPath(),
							EConstants.DEFAULT_SETTINGS_DIRECTORY,"StaffInformation.xml" });
		        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
		        Document doc = docBuilder.parse(new File(ConfigFilePath));
		        
		        // normalize text representation
		        doc.getDocumentElement ().normalize ();
//		        System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
//
		        NodeList listOfValues = doc.getElementsByTagName("Value");
//		        int totalPersons = listOfValues.getLength();
//		        System.out.println("Total no of people : " + totalPersons);

		        for(int s=0; s<listOfValues.getLength() ; s++){
		        	// initilize Staff Info Object
		        	staffInfo=new StaffInfoEntity();
		            Node firstPersonNode = listOfValues.item(s);
		            if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
		                // Set Staff Number
		                staffInfo.setNumber(getNodeValueByKey(firstPersonNode,"No"));
		                // Set Staff Name
		                staffInfo.setName(getNodeValueByKey(firstPersonNode,"Name"));
		                // Set Staff Phone
		                staffInfo.setPhone(getNodeValueByKey(firstPersonNode,"Phone"));
		                // Set Staff Address
		                staffInfo.setAddress(getNodeValueByKey(firstPersonNode,"Addr"));		              
		            }
		            staffInfos.add(staffInfo);
		        }
		    }catch (SAXParseException err) {
		    System.out.println ("** Parsing error" + ", line " 
		         + err.getLineNumber () + ", uri " + err.getSystemId ());
		    System.out.println(" " + err.getMessage ());

		    }catch (SAXException e) {
		    Exception x = e.getException ();
		    ((x == null) ? e : x).printStackTrace ();

		    }catch (Throwable t) {
		    t.printStackTrace ();
		    }
		
    	return staffInfos;
    }
    /**
     * Get Node Value By Key
     * @Title: getNodeValueByKey
     * @Description: TODO
     * @param @param firstPersonNode
     * @param @param key
     * @param @return
     * @return String
     * @throws
     */
	private static String getNodeValueByKey(Node firstPersonNode,String key) {
		Element firstPersonElement = (Element)firstPersonNode;
        NodeList noList = firstPersonElement.getElementsByTagName(key);
        Element noElement = (Element)noList.item(0);
        NodeList textNoList = noElement.getChildNodes();
		return ((Node)textNoList.item(0)).getNodeValue().trim();
	}

	/**
	 * @Title: readStaffInfos
	 * @Description: TODO
	 * @param 
	 * @return void
	 * @throws
	 */
	
	public static void readStaffInfos() {
		try {
			
			String ConfigFilePath = StringUtils.URLPathCombine(new String[] {XmlUtils.class.getClassLoader().getResource("").getPath(),
							EConstants.DEFAULT_SETTINGS_DIRECTORY,"StaffInformation.xml" });
		        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
		        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
		        Document doc = docBuilder.parse(new File(ConfigFilePath));
		        
		        // normalize text representation
		        doc.getDocumentElement ().normalize ();
		        System.out.println ("Root element of the doc is " + 
		             doc.getDocumentElement().getNodeName());


		        NodeList listOfPersons = doc.getElementsByTagName("Value");
		        int totalPersons = listOfPersons.getLength();
		        System.out.println("Total no of people : " + totalPersons);

		        for(int s=0; s<listOfPersons.getLength() ; s++){


		            Node firstPersonNode = listOfPersons.item(s);
		            if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){


		                Element firstPersonElement = (Element)firstPersonNode;

		                //-------
		                NodeList noList = firstPersonElement.getElementsByTagName("No");
		                Element noElement = (Element)noList.item(0);

		                NodeList textNoList = noElement.getChildNodes();
		                System.out.println("No : " + ((Node)textNoList.item(0)).getNodeValue().trim());

		                //-------
		                NodeList nameList = firstPersonElement.getElementsByTagName("Name");
		                Element nameElement = (Element)nameList.item(0);

		                NodeList textNameList = nameElement.getChildNodes();
		                System.out.println("Name : " + ((Node)textNameList.item(0)).getNodeValue().trim());

		                //----
		                NodeList phoneList = firstPersonElement.getElementsByTagName("Phone");
		                Element phoneElement = (Element)phoneList.item(0);

		                NodeList textPhoneList = phoneElement.getChildNodes();
		                System.out.println("Phone : " +((Node)textPhoneList.item(0)).getNodeValue().trim());

		                //------
		                
		                //----
		                NodeList addrList = firstPersonElement.getElementsByTagName("Addr");
		                Element addrElement = (Element)addrList.item(0);

		                NodeList textAddrList = addrElement.getChildNodes();
		                System.out.println("Addr : " + ((Node)textAddrList.item(0)).getNodeValue().trim());

		                //------

		            }//end of if clause
		        }//end of for loop with s var


		    }catch (SAXParseException err) {
		    System.out.println ("** Parsing error" + ", line " 
		         + err.getLineNumber () + ", uri " + err.getSystemId ());
		    System.out.println(" " + err.getMessage ());

		    }catch (SAXException e) {
		    Exception x = e.getException ();
		    ((x == null) ? e : x).printStackTrace ();

		    }catch (Throwable t) {
		    t.printStackTrace ();
		    }
		    //System.exit (0);
	}


}